<?php

namespace App\Mobile\Controllers;

include base_path() . '/vendor/autoload.php';

use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use DB;
use Auth;
use Validator;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Redis;
use App\Agent;
use App\Club;
use App\ClubUser;
use App\RebateLog;
use Log;

class PaymentController extends Controller
{
	/*网页版公众号配置*/
	protected $options = [
	    'debug'  => false,
	    'app_id' => 'wx555be570d21859aa',
	    'secret' => 'f92678be7687d1e1b1471ca9c066f242',
	    'payment' => [
	        'merchant_id' => '1502486801',
	        'key' => 'leyouleyouleyouleyouleyouleyou18',
	    	'cert_path' => '/home/cert/apiclient_cert.pem',
	    	'key_path' => '/home/cert/apiclient_key.pem',
	    ],
	];

	/**
	 * [index 充值]
	 * @return [type] [description]
	 */
	public function index(Agent $agent)
	{
		$orders = \App\Order::where(['user_id' => $agent->id, 'order_status' => 1, 'pay_status' => 1])->whereIn('type', [2,3])->orderBy('created_at', 'DESC')->get();
		return view('mobile.agent.charge', compact('agent', 'orders'));
	}

	/**
	 * [dayPay description]
	 * @return [type] [description]
	 */
	public function dayPay()
	{
		return view('mobile.agent.dayPay');
	}

	/**
	 * [payment 支付]
	 * @return [type] [description]
	 */
	public function payment(Request $request)
	{
		if ($request->input('key') && $request->input('pay')) {//亲友圈套餐购买
			$agent = Auth::guard('mobile')->user();
			$pay = $request->input('pay');
			$key = $request->input('key');
			if ($pay && $key) {
				$out_trade_num = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
				if ($pay == 2) {//288套餐
					$amount = 288;
					$type = 4;
				} else if ($pay == 3) {//888套餐
					$amount = 888;
					$type = 5;
				} else if ($pay == 4) {//1688套餐
					$amount = 1688;
					$type = 6;
				} else if ($pay == 5) {//2188套餐
					$amount = 2188;
					$type = 7;
				} else if ($pay == 6) {//2688套餐
					$amount = 2688;
					$type = 8;
				}
	        	$order = new \App\Order;
	        	$order->order_sn = $out_trade_num;
	        	$order->order_amount = $amount;
	        	$order->type = $type;
	        	$order->user_id = $agent->id;
	        	$order->extra = $key;
	        	$order->save();
	        	/*微信下单*/
	            $attributes = [
	                'trade_type' => 'JSAPI',
	                'body' => '购买亲友圈套餐',
	                'detail' => 'detail',
	                'out_trade_no' => $out_trade_num,
	                'total_fee' => $amount * 100,
	                'notify_url' => 'http://user.leyougame.cc/mobile/agent/payBack',
	                'openid' => $agent->open_id,
	            ];
	    		$app = new Application($this->options);
				$order = new Order($attributes);
				$payment = $app->payment;
				$result = $payment->prepare($order);
				if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
			        $prepayId = $result->prepay_id;
		    		$json = $payment->configForPayment($prepayId);
					return view('/mobile/agent/purchase', ['json' => $json, 'amount' => $amount]);
				} else {
					return back();
				}
			}
		} elseif ($request->input('cid') && $request->input('level')) {//亲友圈套餐续费
			$agent = Auth::guard('mobile')->user();
			$cid = $request->input('cid');
			$level = $request->input('level');
			$out_trade_num = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
			if ($level == 2) {//288套餐续费
				$amount = 288;
				$type = 8;
			} else if ($level == 3) {//888套餐续费
				$amount = 888;
				$type = 9;
			} else if ($level == 4) {//1688套餐续费
				$amount = 1688;
				$type = 10;
			} else if ($level == 5) {//2188套餐续费
				$amount = 2188;
				$type = 11;
			} else if ($level == 6) {//2688套餐续费
				$amount = 2688;
				$type = 12;
			}
			$club = Club::where(['club_id' => $cid])->first();
			if ($club) {
				if (($club->expiry_date/1000) > time()) {//会员还有剩余时间
					$divide_date = ceil((($club->expiry_date / 1000) - time()) / 86400);//剩余天数
					$divide_money = 0;//折现额度
					switch ($club->type) {
						case 2:
							$divide_money = 9.6 * $divide_date;
							break;
						case 3:
							$divide_money = 29.6 * $divide_date;
							break;
						case 4:
							$divide_money = 56 * $divide_date;
							break;
						case 5:
							$divide_money = 72 * $divide_date;
							break;
						case 6:
							$divide_money = 89 * $divide_date;
							break;				
					}
				}
				$amount = $amount - $divide_money;
			}
        	$order = new \App\Order;
        	$order->order_sn = $out_trade_num;
        	$order->order_amount = $amount;
        	$order->type = $type;
        	$order->user_id = $agent->id;
        	$order->extra = $cid;
        	$order->save();
    		/*微信下单*/
            $attributes = [
                'trade_type' => 'JSAPI',
                'body' => '续费亲友圈套餐',
                'detail' => 'detail',
                'out_trade_no' => $out_trade_num,
                'total_fee' => $amount * 100,
                'notify_url' => 'http://user.leyougame.cc/mobile/agent/payBack',
                'openid' => $agent->open_id,
            ];
    		$app = new Application($this->options);
			$order = new Order($attributes);
			$payment = $app->payment;
			$result = $payment->prepare($order);
			if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
		        $prepayId = $result->prepay_id;
	    		$json = $payment->configForPayment($prepayId);
				return view('/mobile/agent/purchase', ['json' => $json, 'amount' => $amount]);
			} else {
				return back();
			}
		} elseif ($request->input('day_pay')) {
			$agent = Auth::guard('mobile')->user();
			$out_trade_num = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
			$amount = 0.01;
    		/*微信下单*/
            $attributes = [
                'trade_type' => 'JSAPI',
                'body' => '续费亲友圈套餐',
                'detail' => 'detail',
                'out_trade_no' => $out_trade_num,
                'total_fee' => $amount * 100,
                'notify_url' => 'http://user.leyougame.cc/mobile/agent/payBack',
                'openid' => $agent->open_id,
            ];
    		$app = new Application($this->options);
			$order = new Order($attributes);
			$payment = $app->payment;
			$result = $payment->prepare($order);
			if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
		        $prepayId = $result->prepay_id;
	    		$json = $payment->configForPayment($prepayId);
				return view('/mobile/agent/purchase', ['json' => $json, 'amount' => $amount]);
			} else {
				return back();
			}
		} else {
			$validator = Validator::make($request->all(), [
				'type' => 'required',
	        ], [
	        	'type.required' => '请选择套餐类型'
	        ]);
	        $agent = Auth::guard('mobile')->user();
	        $out_trade_num = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
	        if ($validator->passes()) {
	        	if ($request->input('type') == 1) {
	        		$amount = 1000;
	        		$type = 2;
	        	} else {
	        		$amount = 2000;
	        		$type = 3;
	        	}
	        	$order = new \App\Order;
	        	$order->order_sn = $out_trade_num;
	        	$order->order_amount = $amount;
	        	$order->type = $type;
	        	$order->user_id = $agent->id;
	        	$order->save();
	        	/*微信下单*/
	            $attributes = [
	                'trade_type' => 'JSAPI',
	                'body' => '购买推广员套餐',
	                'detail' => 'detail',
	                'out_trade_no' => $out_trade_num,
	                'total_fee' => $amount * 100,
	                'notify_url' => 'http://user.leyougame.cc/mobile/agent/payBack',
	                'openid' => $agent->open_id,
	            ];
	    		$app = new Application($this->options);
				$order = new Order($attributes);
				$payment = $app->payment;
				$result = $payment->prepare($order);
				if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
			        $prepayId = $result->prepay_id;
		    		$json = $payment->configForPayment($prepayId);
					return view('/mobile/agent/purchase', ['json' => $json, 'amount' => $amount]);
				} else {
					return back();
				}
	        } else {
	            return Redirect::back()->withInput()->withErrors($validator->errors());
	        }			
		}
	}

	/**
	 * [paySuccess 支付成功]
	 * @return [type] [description]
	 */
	public function paySuccess()
	{
  		$agent = Auth::guard('mobile')->user();
  		return view('mobile.agent.success', compact('agent'));
	}

	/**
	 * [payBack 异步通知接口]
	 * @return [type] [description]
	 */
	public function payBack()
	{
		$app = new Application($this->options);
		$payment = $app->payment;
		$response = $app->payment->handleNotify(function($notify, $successful){
			Log::info('-------successful----------'.$successful);
		    // 用户是否支付成功
		    if ($successful) {
		        $order_arr = json_decode($notify, true);
	            $order_sn = $order_arr['out_trade_no'];
	            $order = \App\Order::where('order_sn', $order_sn)->first();
	            if($order){
	            	if ($order->type == 2) {//购买推广员套餐5200张
		            	$order->order_status = 1;
			            $order->pay_status = 1;
			            $order->pay_time = date('Y-m-d H:i:s', time());
			            $order->save();
			            $agent = Agent::where(['id' => $order->user_id])->first();
			            if ($agent) {
			            	$user = $agent->user();
			            	if ($user) {
			            		$user->gems += 5200;
			            		$user->save();
			            	}
			            }
	            	}
	            	if ($order->type == 3) {//购买推广员套餐11000张
		            	$order->order_status = 1;
			            $order->pay_status = 1;
			            $order->pay_time = date('Y-m-d H:i:s', time());
			            $order->save();
			            $agent = Agent::where(['id' => $order->user_id])->first();
			            if ($agent) {
			            	$user = $agent->user;
			            	if ($user) {
			            		$user->gems += 11000;
			            		$user->save();
			            	}
			            }
	            	}
	            	if ($order->type == 4) {//购买亲友圈套餐288
		            	$order->order_status = 1;
			            $order->pay_status = 1;
			            $order->pay_time = date('Y-m-d H:i:s', time());
			            $order->save();
			            $agent = Agent::where(['id' => $order->user_id])->first();
			            if ($agent) {
			            	$info = Redis::get($order->extra);
			            	if ($info) {
			            		$info = json_decode($info, true);
			            		$club = new Club;
			            		$club->club_id = $this->generateClubId();
			            		$club->club_name = base64_encode($info['club_name']);
			            		$club->creator = $agent->user()->userid;
			            		$club->create_time = time();
			            		$club->hotpush = 1;
			            		$club->description = $info['description'];
			            		$club->maxrooms = 5;
			            		$club->limitpeople = 30;
			            		$club->type = 2;
			            		$club->expiry_date = (time() + 2592000) * 1000;
			            		$club->save();
			            		$club_user = new ClubUser;
			            		$club_user->club_id = $club->club_id;
			            		$club_user->userid = $agent->user()->userid;
			            		$club_user->join_time = time();
			            		$club_user->state = 999;
			            		$club_user->save();
			            		Redis::del($order->extra);
			            	}
			            	/*判断是否给上级代理分成*/
			            	if ($agent->pid != 0) {//有上级代理
			            		$parent_agent = Agent::where(['id' => $agent->pid])->first();
			            		if ($parent_agent && $parent_agent->circle_divide > 0) {//满足分成条件
			            			$fee = 288 * ($parent_agent->circle_divide / 100);//分成金额
			            			$parent_agent->money += $fee;//返利至上级代理钱包内
			            			$parent_agent->save();
			            			/*记录返利日志*/
			            			$log = new RebateLog;
			            			$log->order_sn = $order_sn;
			            			$log->type = 3;
			            			$log->daili_id = $parent_agent->id;
			            			$log->second_id = $agent->id;
			            			$log->fee = $fee;
			            			$log->save();
			            		}
			            	}
			            }
	            	} 
	            	if ($order->type == 5) {//购买亲友圈套餐888
		            	$order->order_status = 1;
			            $order->pay_status = 1;
			            $order->pay_time = date('Y-m-d H:i:s', time());
			            $order->save();
			            $agent = Agent::where(['id' => $order->user_id])->first();
			            if ($agent) {
			            	$info = Redis::get($order->extra);
			            	if ($info) {
			            		$info = json_decode($info, true);
			            		$club = new Club;
			            		$club->club_id = $this->generateClubId();
			            		$club->club_name = base64_encode($info['club_name']);
			            		$club->creator = $agent->user()->userid;
			            		$club->create_time = time();
			            		$club->hotpush = 1;
			            		$club->description = $info['description'];
			            		$club->maxrooms = 7;
			            		$club->limitpeople = 60;
			            		$club->type = 3;
			            		$club->expiry_date = (time() + 2592000) * 1000;
			            		$club->save();
			            		$club_user = new ClubUser;
			            		$club_user->club_id = $club->club_id;
			            		$club_user->userid = $agent->user()->userid;
			            		$club_user->join_time = time();
			            		$club_user->state = 999;
			            		$club_user->save();
			            		Redis::del($order->extra);
			            	}
			            	/*判断是否给上级代理分成*/
			            	if ($agent->pid != 0) {//有上级代理
			            		$parent_agent = Agent::where(['id' => $agent->pid])->first();
			            		if ($parent_agent && $parent_agent->circle_divide > 0) {//满足分成条件
			            			$fee = 888 * ($parent_agent->circle_divide / 100);//分成金额
			            			$parent_agent->money += $fee;//返利至上级代理钱包内
			            			$parent_agent->save();
			            			/*记录返利日志*/
			            			$log = new RebateLog;
			            			$log->order_sn = $order_sn;
			            			$log->type = 3;
			            			$log->daili_id = $parent_agent->id;
			            			$log->second_id = $agent->id;
			            			$log->fee = $fee;
			            			$log->save();
			            		}
			            	}
			            }
	            	} 
	            	if ($order->type == 6) {//购买亲友圈套餐1688
		            	$order->order_status = 1;
			            $order->pay_status = 1;
			            $order->pay_time = date('Y-m-d H:i:s', time());
			            $order->save();
			            $agent = Agent::where(['id' => $order->user_id])->first();
			            if ($agent) {
			            	$info = Redis::get($order->extra);
			            	if ($info) {
			            		$info = json_decode($info, true);
			            		$club = new Club;
			            		$club->club_id = $this->generateClubId();
			            		$club->club_name = base64_encode($info['club_name']);
			            		$club->creator = $agent->user()->userid;
			            		$club->create_time = time();
			            		$club->hotpush = 1;
			            		$club->description = $info['description'];
			            		$club->maxrooms = 9;
			            		$club->limitpeople = 90;
			            		$club->type = 4;
			            		$club->expiry_date = (time() + 2592000) * 1000;
			            		$club->save();
			            		$club_user = new ClubUser;
			            		$club_user->club_id = $club->club_id;
			            		$club_user->userid = $agent->user()->userid;
			            		$club_user->join_time = time();
			            		$club_user->state = 999;
			            		$club_user->save();
			            		Redis::del($order->extra);
			            	}
			            	/*判断是否给上级代理分成*/
			            	if ($agent->pid != 0) {//有上级代理
			            		$parent_agent = Agent::where(['id' => $agent->pid])->first();
			            		if ($parent_agent && $parent_agent->circle_divide > 0) {//满足分成条件
			            			$fee = 1688 * ($parent_agent->circle_divide / 100);//分成金额
			            			$parent_agent->money += $fee;//返利至上级代理钱包内
			            			$parent_agent->save();
			            			/*记录返利日志*/
			            			$log = new RebateLog;
			            			$log->order_sn = $order_sn;
			            			$log->type = 3;
			            			$log->daili_id = $parent_agent->id;
			            			$log->second_id = $agent->id;
			            			$log->fee = $fee;
			            			$log->save();
			            		}
			            	}
			            }
	            	} 	
	            	if ($order->type == 7) {//购买亲友圈套餐2188
		            	$order->order_status = 1;
			            $order->pay_status = 1;
			            $order->pay_time = date('Y-m-d H:i:s', time());
			            $order->save();
			            $agent = Agent::where(['id' => $order->user_id])->first();
			            if ($agent) {
			            	$info = Redis::get($order->extra);
			            	if ($info) {
			            		$info = json_decode($info, true);
			            		$club = new Club;
			            		$club->club_id = $this->generateClubId();
			            		$club->club_name = base64_encode($info['club_name']);
			            		$club->creator = $agent->user()->userid;
			            		$club->create_time = time();
			            		$club->hotpush = 1;
			            		$club->description = $info['description'];
			            		$club->maxrooms = 11;
			            		$club->limitpeople = 120;
			            		$club->type = 5;
			            		$club->expiry_date = (time() + 2592000) * 1000;
			            		$club->save();
			            		$club_user = new ClubUser;
			            		$club_user->club_id = $club->club_id;
			            		$club_user->userid = $agent->user()->userid;
			            		$club_user->join_time = time();
			            		$club_user->state = 999;
			            		$club_user->save();
			            		Redis::del($order->extra);
			            	}
			            	/*判断是否给上级代理分成*/
			            	if ($agent->pid != 0) {//有上级代理
			            		$parent_agent = Agent::where(['id' => $agent->pid])->first();
			            		if ($parent_agent && $parent_agent->circle_divide > 0) {//满足分成条件
			            			$fee = 2188 * ($parent_agent->circle_divide / 100);//分成金额
			            			$parent_agent->money += $fee;//返利至上级代理钱包内
			            			$parent_agent->save();
			            			/*记录返利日志*/
			            			$log = new RebateLog;
			            			$log->order_sn = $order_sn;
			            			$log->type = 3;
			            			$log->daili_id = $parent_agent->id;
			            			$log->second_id = $agent->id;
			            			$log->fee = $fee;
			            			$log->save();
			            		}
			            	}
			            }
	            	}
	            	if ($order->type == 8) {//购买亲友圈套餐2688
		            	$order->order_status = 1;
			            $order->pay_status = 1;
			            $order->pay_time = date('Y-m-d H:i:s', time());
			            $order->save();
			            $agent = Agent::where(['id' => $order->user_id])->first();
			            if ($agent) {
			            	$info = Redis::get($order->extra);
			            	if ($info) {
			            		$info = json_decode($info, true);
			            		$club = new Club;
			            		$club->club_id = $this->generateClubId();
			            		$club->club_name = base64_encode($info['club_name']);
			            		$club->creator = $agent->user()->userid;
			            		$club->create_time = time();
			            		$club->hotpush = 1;
			            		$club->description = $info['description'];
			            		$club->maxrooms = 15;
			            		$club->limitpeople = 150;
			            		$club->type = 5;
			            		$club->expiry_date = (time() + 2592000) * 1000;
			            		$club->save();
			            		$club_user = new ClubUser;
			            		$club_user->club_id = $club->club_id;
			            		$club_user->userid = $agent->user()->userid;
			            		$club_user->join_time = time();
			            		$club_user->state = 999;
			            		$club_user->save();
			            		Redis::del($order->extra);
			            	}
			            	/*判断是否给上级代理分成*/
			            	if ($agent->pid != 0) {//有上级代理
			            		$parent_agent = Agent::where(['id' => $agent->pid])->first();
			            		if ($parent_agent && $parent_agent->circle_divide > 0) {//满足分成条件
			            			$fee = 2688 * ($parent_agent->circle_divide / 100);//分成金额
			            			$parent_agent->money += $fee;//返利至上级代理钱包内
			            			$parent_agent->save();
			            			/*记录返利日志*/
			            			$log = new RebateLog;
			            			$log->order_sn = $order_sn;
			            			$log->type = 3;
			            			$log->daili_id = $parent_agent->id;
			            			$log->second_id = $agent->id;
			            			$log->fee = $fee;
			            			$log->save();
			            		}
			            	}
			            }
	            	} 	
	            	if ($order->type == 8 || $order->type == 9 || $order->type == 10 || $order->type == 11 || $order->type == 12) {//续费288套餐或888套餐或1688套餐或2188套餐或2688套餐
		            	$order->order_status = 1;
			            $order->pay_status = 1;
			            $order->pay_time = date('Y-m-d H:i:s', time());
			            $order->save();
			            $limitpeople = 30;//人数上限
			            $maxrooms = 5;//房间上限
			            $packet_fee = 288;//套餐价格
			            switch($order->type){
			            	case 8:
					            $limitpeople = 30;
					            $maxrooms = 5;
					            $packet_fee = 288;
			            		break;
			            	case 9:
				            	$limitpeople = 60;
					            $maxrooms = 7;
					            $packet_fee = 888;
			            		break;
			            	case 10:
				            	$limitpeople = 90;
					            $maxrooms = 9;
					            $packet_fee = 1688;
			            		break;
			            	case 11:
			            		$limitpeople = 120;
					            $maxrooms = 11;
					            $packet_fee = 2188;
			            		break;
			            	case 12:
			            		$limitpeople = 150;
					            $maxrooms = 15;
					            $packet_fee = 2688;
			            		break;	
			            }
			            $club = Club::where(['club_id' => $order->extra])->update(['expiry_date' => (time() + 2592000) * 1000, 'maxrooms' => $maxrooms, 'limitpeople' => $limitpeople]);
			            $agent = Agent::where(['id' => $order->user_id])->first();
			            if ($agent) {
			            	if ($agent->pid != 0) {//有上级代理
			            		$parent_agent = Agent::where(['id' => $agent->pid])->first();
		            			if ($parent_agent && $parent_agent->circle_divide > 0) {//满足分成条件
			            			$fee = $packet_fee * ($parent_agent->circle_divide / 100);//分成金额
			            			$parent_agent->money += $fee;//返利至上级代理钱包内
			            			$parent_agent->save();
			            			/*记录返利日志*/
			            			$log = new RebateLog;
			            			$log->order_sn = $order_sn;
			            			$log->type = 3;
			            			$log->daili_id = $parent_agent->id;
			            			$log->second_id = $agent->id;
			            			$log->fee = $fee;
			            			$log->save();
		            			}
		            		}
			            }	
	            	}	            	            	            	         	            	
	            }
		    } 
		    return true; // 返回处理完成
		});
		return $response;
	}

	/**
	 * [generateClubId 生成俱乐部id]
	 * @return [type] [description]
	 */
	public function generateClubId()
	{
		$id = rand(100000, 999999);
		$exist = Club::where(['club_id' => $id])->first();
		if ($exist) {
			$this->generateClubId();
		} else {
			return $id;
		}
	}

}	